#!/usr/bin/python3 
# -*- coding: utf-8 -*-
"""
@File Name  : root.py
@Author     : LeeCQ
@Date-Time  : 2020/1/3 19:16

Content-Length

"""
import sys, logging

logger = logging.getLogger("logger")  # 创建实例
formatter = logging.Formatter("[%(asctime)s] < %(funcName)s: %(thread)d > [%(levelname)s] %(message)s")
# 终端日志
consle_handler = logging.StreamHandler(sys.stdout)
consle_handler.setFormatter(formatter)  # 日志文件的格式
logger.setLevel(logging.DEBUG)  # 设置日志文件等级

import requests, json, os, urllib3
from SQL.MySQL import MyMySqlAPI


class FanDengError(Exception): pass
class BooksListError(FanDengError): pass
#


class FDSQL(MyMySqlAPI):
    def __init__(self, **kwargs):

        self.SQL_HOST = 't.sql.leecq.xyz'  # 主机
        self.SQL_PORT = 10080  # 端口
        self.SQL_USER = 'book'  # 用户
        self.SQL_PASSWD = 'book123456'  # 密码
        self.SQL_DB = 'book'  # 数据库
        self.SQL_CHARSET = 'gb18030'  # 编码
        super().__init__(host=self.SQL_HOST,
                         port=self.SQL_PORT,
                         user=self.SQL_USER,
                         passwd=self.SQL_PASSWD,
                         db=self.SQL_DB,
                         charset=self.SQL_CHARSET,
                         **kwargs
                         )
        self.TABLE_PREFIX = 'FD_'

    def create_table_FanDengReader(self):
        _c = ("bookID       INT(4) UNIQUE NOT NULL  , "
              "name         VARCHAR(50)   NOT NULL  , "
              "fragmentID   VARCHAR(50)   NOT NULL  , "
              "coverURL     VARCHAR(110)  NOT NULL  , "
              "mp3URL       VARCHAR(110)    , "
              "m3u8URL      VARCHAR(110)    , "
              "createTime   INT(4)       , "
              "lastUpdate   INT(4)       "
              )
        _a = "default charset=gb18030; "
        self.create_table(_c, table_name='Books', table_args=_a)


class FanDengReader:
    """"""

    def __init__(self, retry=5, timeout=30, debug_level=3, strict_mode=True,
                 ):
        self.retry = retry
        self.timeout = timeout
        self.debug_level = debug_level
        self.strict_mode = strict_mode
        #
        os.makedirs('./sup', exist_ok=True)
        self.f_booksList = './sup/booksList.json'
        # 模拟客户端会话
        self.client = requests.Session()
        self.client.verify = False
        self.client_set_header()

    def header_cookie(self):
        """樊登读书的Headers，"""
        pass

    def client_set_cookie(self, cookie=None):
        """"""
        if cookie is None:
            cookie = {

                }
        self.client.cookies(cookie)

    def client_set_header(self, header=None):
        if header is None:
            header = {
                "Host": "api.dushu.io",
                "Accept": "*/*",
                "Accept-Encoding": "br, gzip, deflate",
                "Content-Type": "application/json; charset=utf-8",
                "User-Agent": "bookclub/4.0.0 (iPhone; iOS 12.2; Scale/2.00)",
                "Accept-Language": "en-CN;q=1, zh-Hans-CN;q=0.9",
                "Connection": "keep-alive",
                }
        header.setdefault("X-DUSHU-APP-VER", "4.0.0")
        header.setdefault("X-DUSHU-APP-PLT", "1")
        header.setdefault("X-DUSHU-APP-MUID", "C6C7D37C-6BBE-4EBD-AF0F-F46B10550697")
        header.setdefault("X-DUSHU-APP-SYSVER", "Version 12.2 (Build 16E227)")
        header.setdefault("X-DUSHU-APP-DEVID", "324A1831-96E6-437F-BA2A-8D2362AEFA68")
        header.setdefault("X-DUSHU-APP-DEVTOKEN", "0e2928ab46bec662da25f277f6c12df89ea76b40a946e318473576209a676ec1")
        self.client.headers.update(header)

    # 获取书籍列表 -
    def booksList(self):
        """获取书籍列表

        :return list -
        """
        url = 'https://api.dushu.io/books'
        data = '{"bookReadStatus":-1,"order":1,"pageSize":1000,"page":1}'
        n = self.retry
        while n:
            n -= 1
            json_ = self.client.post(url=url, data=data, headers={'Content-Length': str(len(data))})
            if json_.status_code == 200:
                booksInfo = json.loads(json_.text)
                if booksInfo["totalCount"] == len(booksInfo["books"]):
                    if 'fragmentId' in booksInfo['books'][0]['contents'][1].keys():
                        with open(self.f_booksList, 'w', encoding='gbk') as f:
                            f.write(json.dumps(booksInfo["books"]))
                        if self.debug_level >= 3:
                            logger.info(f'获取书籍列表完成...共{len(booksInfo["books"])}本')
                        return booksInfo["books"]
                    else:
                        logger.error(f'获取的书籍列表中没有：fragmentId 字段，token过期可能！')
                        if self.strict_mode:
                            raise BooksListError("信息监测：fragmentId字段未找到！")
            else:
                logger.warning(f'URL:[{json_.status_code}]{url}异常返回！')
        if self.strict_mode:
            raise
        return 'Error'

    # 获取一本书的书籍的详细信息：
    def book_oneDetail(self, book: dict, token=None):
        """获取书籍的详细信息：

            主要是通过：contents.fragmentID 拉取详细信息
                contents[0] = {
                            "fragmentId": 200003794,
                            "mediaDuration": 0,
                            "memberOnly": true,
                            "type": 1  --
                            }
                type: 1 --> 书籍的页面信息
                type: 2 --> 音频  时间大于7 min
                type: 3 --> 视频  playlist.m3u8 大于700行

            得到的是JSON字符串：>> trial = False << 为全文
        :return: dict - {name, fragmentID, mp3URL, m3u8URL, bookCoverURL, LastUpdateTime, CreateTime}
        """
        def get_info(data_):
            info = self.client.post(url, data_, headers={'Content-Length': str(len(data))})
            if info.status_code == 200:
                bookInfo = json.loads(info.text)
                if bookInfo['t']
                return bookInfo

        if token is None:
            token = "20200103paGqXp12pzS11Z3NaTo"
        url = 'https://api.dushu.io/fragment/content'
        contents = book['contents']
        mp3URL, m3u8URL, bookContent, lastUpdateTime = None, None, None, None
        for _content in contents:
            fragment_id = _content
            if _content['type'] == 1:
                pass
            elif _content['type'] == 2:
                data = f'{{"fragmentId":{fragment_id},"albumId":0,"token":{token},"programId":0}}'
                data = get_info(data)
                mp3URL = data['mediaUrls']
                bookContent = data['content']
                lastUpdateTime = data['lastUpdateTime']
            elif _content == 3:
                data = f'{{"fragmentId":{fragment_id},"albumId":-8888888,"token":{token},"programId":-8888888}}'
                m3u8URL = get_info(data)['mediaUrls']
            else:
                raise
        return {'idd': book['id'],
                'bookName': book['title'],
                'summary': book['summary'],
                'fragmentID': {'type1': contents[0]['fragmentID'],
                               'type2': contents[1]['fragmentID'],
                               'type3': contents[2]['fragmentID'],
                               },
                'createTime': book['createTime'],
                'lastUpdateTime': lastUpdateTime,
                'coverURL': book['imageUrl'],
                'introduction': bookContent,    # type1
                'mp3URL': mp3URL,               # type2
                'm3u8URL': m3u8URL,             # type3
                }

    def detail_type1(self):
        pass

    def detail_type2(self):
        pass

    def detail_type3(self):
        pass


if __name__ == '__main__':
    logger.addHandler(consle_handler)  #
    urllib3.disable_warnings()

    a = FanDengReader().book_oneDetail(3138)
    # print(a, len(a))
    # a = FDSQL().create_table_FanDengReader()
    print(a)
